using System;
using System.Data.SqlClient;
using System.Data;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Data.SqlTypes;
using System.Text;
using System.Text.RegularExpressions;
using LogCMS.DAL;

namespace Portal.BO.Editoral.Statistic
{
	/// <summary>
	/// Summary description for Log.
	/// </summary>
    /// 
    public enum CountKey : byte
    {
        All_View = 1,
        Home_View = 2,
        Category_View = 3,
        Content_View = 4,
        Error_500 = 5,
        Category_Wait_Edit_Content = 6,
        Category_Wait_Approve_Content = 7,
        Category_Approved_Content = 8,
        UNIQUE_USER_ACCESS = 9,
        UNIQUE_IP = 10,
        User_Wait_Edit_Content = 11,
        User_Wait_Approve_Content = 12,
        User_Approved_Content = 13,
        Custom_User_View = 14
    }

	public class Log {
		public HttpContext context;



        private DateTime GetLastAccess(string IPAddress)
		{
            DateTime retval;
            
            using (MainDB db = new MainDB())
            {
                DataTable dt = db.StoredProcedures.Log_GetIP(IPAddress);
                try {
                    if (dt.Rows[0]["LastAccess"] != null)
                    {
                        retval = Convert.ToDateTime(dt.Rows[0]["LastAccess"]);
                    }
                    else {
                        retval = DateTime.MaxValue;
                    }
                    
                }
                catch{
                    retval = DateTime.MaxValue;
                }
                
            }

            return retval;
		}
        //private void UpdateLastAccess(string IPAddress)
        //{
        //    //
        //    SqlCommand Command = new SqlCommand("Log_UpdateIP", Log_Conn);
        //    Command.CommandType = CommandType.StoredProcedure;

        //    Command.Parameters.Add(new SqlParameter("@IPAddress", SqlDbType.VarChar));
        //    Command.Parameters["@IPAddress"].Value = IPAddress;
        //    Command.Parameters.Add(new SqlParameter("@LastAccess", SqlDbType.DateTime));
        //    Command.Parameters["@LastAccess"].Value = DateTime.Now;		
			
        //    Command.Connection.Open();
        //    try 
        //    {
        //        Command.ExecuteNonQuery();				
        //    }
        //    finally 
        //    {
        //        Command.Connection.Close();			
        //    }
			
        //}

        public Int64 GetCurrentLogInfo(int LogType, string LogObject_ID)
		{
			
            Int64 retval = -1;

            using (MainDB db = new MainDB())
            {
                DataTable dt = db.StoredProcedures.Log_GetCurrentLogInfo(LogObject_ID, LogType, DateTime.Now);
                if(dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["Log_Sum_Value"] != null)
                    {
                        retval = Convert.ToInt32(dt.Rows[0]["Log_Sum_Value"]);
                    }
                    else
                    {
                        retval = 0;
                    }

                }
                else
                {
                    retval = 0;
                }

            }

           
			return retval;

		}

        //private void InsertNewIP(string IPAddress)
        //{
        //    SqlCommand Command = new SqlCommand("Log_InsertIP", Log_Conn);
        //    Command.CommandType = CommandType.StoredProcedure;

        //    Command.Parameters.Add(new SqlParameter("@IPAddress", SqlDbType.VarChar));
        //    Command.Parameters["@IPAddress"].Value = IPAddress;
        //    Command.Parameters.Add(new SqlParameter("@LastAccess", SqlDbType.DateTime));
        //    Command.Parameters["@LastAccess"].Value = DateTime.Now;

        //    Command.Connection.Open();
        //    try
        //    {
        //        Command.ExecuteNonQuery();
        //    }
        //    finally
        //    {
        //        Command.Connection.Close();
        //    }
        //}
		public void IP_Log()
		{
            
			DateTime last_access;
			string userIP= context.Request.UserHostAddress;
			last_access=GetLastAccess(userIP);
			if (last_access != DateTime.MaxValue)
			{
				if (DateTime.Now > last_access)
				{
					// Thong ke so lan IP access vao he thong
                    if (DateTime.Today > last_access)
                        UpdateLogInfo((int)CountKey.UNIQUE_IP);
					
                    // Cap nhap ngay gio cuoi cung cua IP access vao he thong
                    using (MainDB db = new MainDB())
                    {
                        db.StoredProcedures.Log_UpdateIP(userIP, DateTime.Now);
                    }
				}
			}
			else
			{
                // Neu IP nay chua access vao he thong
                UpdateLogInfo((int)CountKey.UNIQUE_IP);
                using (MainDB db = new MainDB())
                {
                    db.StoredProcedures.LOG_InsertIP(userIP, DateTime.Now);
                }
			}

		}
		private void UpdateUserCookie()
		{
			string user_cookie= DateTime.Now.Year.ToString("0000")+DateTime.Now.Month.ToString("00")+DateTime.Now.Day.ToString("00");
			HttpCookie last_access = new HttpCookie("Last_Access",user_cookie);
			last_access.Expires = DateTime.Now.AddYears(99);
			context.Response.Cookies.Add(last_access);
		}

		public void user_log()
		{
			string user_date=null;
			if (context.Request.Cookies.Get("Last_Access")!=null)
			user_date=context.Request.Cookies.Get("Last_Access").Value;

			if (user_date!=null)
			{
				if (user_date.Length==8)
				{
					int y,m,d;
					y=Convert.ToInt32( user_date.Substring(0,4));
					m=Convert.ToInt32( user_date.Substring(4,2));
					d=Convert.ToInt32( user_date.Substring(6,2));
					DateTime last= new DateTime(y,m,d);
					DateTime today= new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day);
					if (last<today)
					{
						UpdateLogInfo((int)CountKey.UNIQUE_USER_ACCESS);
						UpdateUserCookie();
					}
				}
				else
				{

                    UpdateLogInfo((int)CountKey.UNIQUE_USER_ACCESS);
					UpdateUserCookie();
			
				}
			}
			else
			{

                UpdateLogInfo((int)CountKey.UNIQUE_USER_ACCESS);
				UpdateUserCookie();
			
			}
		}

		public Log() {
            context = HttpContext.Current;
		}

        

        
        public void UpdateLogInfo(int LogType)
        {
            UpdateLogInfo(LogType, "-1");
		}

        public void UpdateLogInfo(int LogType, string LogObject_ID)
        {
			
            using (MainDB db = new MainDB())
            {
                if (LogType == (int)CountKey.All_View) {

                    LogObject_ID = "1";
                    db.StoredProcedures.Log_UpdateLog_AllView(LogObject_ID, LogType, DateTime.Today);
                }
                else
                {
                    db.StoredProcedures.Log_UpdateLog(LogObject_ID, LogType, DateTime.Today);
                }
            }
		}
	}
}
